class BooksController < ApplicationController
  before_filter :login_required, :except => [:show]
  before_filter :unread_messages_amount, :only => [:new, :edit, :show]
  
  include BooksHelper
  
  def new
    @book = Book.new
  end
  
  def create
    @book = Book.new(params[:book])
    @book.user = current_user
    @cover = BookCover.new(:uploaded_data => params[:book][:cover])
    @book.book_cover = @cover
    Book.transaction do 
      @book.save!
      @cover.save! if @cover.size
    end
    flash[:notice] = "图书信息已添加"
    redirect_to book_manage_url
  end
  
  def edit
    @book = Book.find(params[:id], :include => :book_cover)
  end
  
  def update
    @book = Book.find(params[:id])
    @book.user = current_user
    @cover = @book.book_cover
    Book.transaction do
      @book.update_attributes(params[:book])
      @cover.update_attributes(:uploaded_data => params[:book][:cover])
    end
    flash[:notice] = "图书信息修改完成"
    redirect_to book_manage_url
  end
  
  def destroy
    @book = Book.find(params[:id])
    @book.destroy
    flash[:notice] = "#{@book.title}已经被删除"
    redirect_to book_manage_url
  end
  
  def show
    @book = Book.find(params[:id])
  end
  
  private
  def authorized?
    logged_in? && self.current_user.is_admin?
  end
  
  def access_denied
    flash[:notice] = "你没有管理图书数据的权限"
    redirect_to :controller => '/admin/general', :action => 'index'
  end
  
end
